const QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
const config = require('../../config.js');

// 实例化API核心类
const qqmapsdk = new QQMapWX({
  key: config.mapKey
});

Page({
  data: {
    meetingInfo: {},
    downloadProgress: 36,
    reasonLength: 0,
    reason: '',
    mid: '',
    distance: 0,  // 添加距离字段
    signStatus: '' // 添加签到状态
  },

  onLoad(options) {
    if (options.mid) {
      this.setData({
        mid: options.mid
      })
      this.getMeetingDetail(options.mid)
    }
  },

  // 检查签到时间状态
  checkSignStatus() {
    const now = new Date().getTime();
    const startTime = new Date(this.data.meetingInfo.startTime).getTime();
    const endTime = new Date(this.data.meetingInfo.endTime).getTime();
    
    let status = '';
    if (this.data.meetingInfo.status === '已签到') {
      status = '已签到';
    } else if (now < startTime) {
      status = '未开始';
    } else if (now > endTime) {
      status = '已结束';
    } else {
      status = '进行中';
    }
    
    this.setData({
      signStatus: status
    });
  },

  getMeetingDetail(id) {
    const app = getApp()
    app.meetingApi.meetingDetail(id).then(res => {
      this.setData({
        meetingInfo: res.data.data,
        reasonLength: res.data.data.reason ? res.data.data.reason.length : 0
      })
      this.checkSignStatus(); // 获取详情后检查签到状态
      console.log(res.data)
    })
  },

  downloadFile() {
    // TODO: 实现文件下载逻辑
    wx.showLoading({
      title: '下载中...',
    })

    // 模拟下载进度
    let progress = 0
    const timer = setInterval(() => {
      progress += 10
      if (progress > 100) {
        clearInterval(timer)
        wx.hideLoading()
        wx.showToast({
          title: '下载完成',
          icon: 'success'
        })
        return
      }
      this.setData({
        downloadProgress: progress
      })
    }, 500)
  },

  signIn() {
    // 先检查签到状态
    if (this.data.signStatus === '未开始') {
      wx.showToast({
        title: '签到还未开始',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.signStatus === '已结束') {
      wx.showToast({
        title: '签到已结束，你未签到',
        icon: 'none'
      });
      return;
    }

    console.log('开始签到流程')
    
    // 先检查是否已授权
    wx.authorize({
      scope: 'scope.userLocation',
      success: () => {
        this.getLocationAndSign()
      },
      fail: () => {
        wx.showModal({
          title: '需要位置权限',
          content: '签到功能需要获取您的位置信息，请授权',
          success: (res) => {
            if (res.confirm) {
              wx.openSetting({
                success: (settingRes) => {
                  if (settingRes.authSetting['scope.userLocation']) {
                    this.getLocationAndSign()
                  }
                }
              })
            }
          }
        })
      }
    })
  },

  getLocationAndSign() {
    wx.showLoading({
      title: '获取位置中...'
    })
    
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        wx.hideLoading()
        const userLatitude = res.latitude
        const userLongitude = res.longitude

        // 获取用户当前位置的地址信息
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: userLatitude,
            longitude: userLongitude
          },
          success: (addressRes) => {
            console.log('用户当前位置地址:', addressRes.result.address)
          }
        })
        
        this.getSignLocation().then(signLocation => {
          const distance = this.calculateDistance(
            userLatitude,
            userLongitude, 
            signLocation.latitude,
            signLocation.longitude
          )
          
          this.setData({
            distance: Math.round(distance)
          })
          
          if(distance <= 800) {
            wx.showLoading({
              title: '签到中...'
            })
            const app = getApp()
            app.meetingApi.toSign(this.data.mid).then(res => {   
              if (res.data.code === 200) {
                this.setData({
                  "meetingInfo.status": '已签到',
                  signStatus: '已签到'
                })
                wx.showToast({
                  title: '签到成功',
                  icon: 'success'
                })
              }
            })
          } else {
            wx.showToast({
              title: `不在签到范围内，距离${Math.round(distance)}米`,
              icon: 'none'
            })
          }
        }).catch(err => {
          wx.showToast({
            title: '地址解析失败',
            icon: 'none'
          })
        })
      },
      fail: (err) => {
        wx.hideLoading()
        wx.showModal({
          title: '获取位置失败',
          content: '请确保已开启定位权限，并且在可以定位的环境下使用',
          showCancel: false
        })
      }
    })
  },

  // 通过地址解析获取经纬度
  getSignLocation() {
    return new Promise((resolve, reject) => {
      const address = this.data.meetingInfo.location2
      
      // 先检查缓存
      const cache = wx.getStorageSync('sign_address_cache') || {};
      if (cache[address]) {
        console.log('使用缓存的地址坐标');
        return resolve(cache[address]);
      }
      
      qqmapsdk.geocoder({
        address: address,
        success: (res) => {
          if (res.status === 0) {
            const location = res.result.location
            const result = {
              latitude: location.lat,
              longitude: location.lng
            };
            
            // 存入缓存
            cache[address] = result;
            wx.setStorageSync('sign_address_cache', cache);
            
            resolve(result)
          } else {
            reject(new Error('地址解析失败'))
          }
        },
        fail: reject
      })
    })
  },

  calculateDistance(lat1, lng1, lat2, lng2) {
    const R = 6371000 // 地球半径(米)
    const dLat = this.toRad(lat2 - lat1)
    const dLng = this.toRad(lng2 - lng1)
    const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) * 
      Math.sin(dLng/2) * Math.sin(dLng/2)
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
    return R * c
  },

  toRad(d) {
    return d * Math.PI / 180
  },

  inputReason(e) {
    this.setData({
      reason: e.detail.value,
      reasonLength: e.detail.value.length
    })
  },

  submitReason() {
    if (!this.data.reason.trim()) {
      wx.showToast({
        title: '请输入原因',
        icon: 'none'
      })
      return
    }

    wx.showModal({
      title: '请确认',
      content: '确定要提交原因吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '提交中...',
          })

          const app = getApp()
          app.meetingApi.submitReason({
            reason: this.data.reason,
            mid: this.data.mid
          }).then(res => {
            if (res.data.code === 200) {
              this.setData({
                meetingInfo: res.data.data
              })
              wx.hideLoading()
              wx.showToast({
                title: '提交成功'
              })
            } else {
              wx.showToast({
                title: '提交失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },

  onPullDownRefresh() {
    this.getMeetingDetail(this.data.mid)
    setTimeout(() => {
      wx.stopPullDownRefresh()
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1000
      })
    }, 1000)
  }
})